package com.hrsoft.edi.stub.internal;

import com.hrsoft.edi.util.BaseContextHandler;
import com.qimen.api.QimenClient;
import com.qimen.api.QimenRequest;
import com.qimen.api.QimenResponse;
import com.taobao.api.ApiException;
import com.taobao.api.Constants;
import com.taobao.api.TaobaoParser;
import com.taobao.api.internal.cluster.ClusterManager;
import com.taobao.api.internal.cluster.DnsConfig;
import com.taobao.api.internal.parser.xml.QimenXmlParser;
import com.taobao.api.internal.util.*;

import java.io.IOException;
import java.net.Proxy;
import java.net.URL;
import java.util.Date;

public class CustomerQimenClient implements QimenClient
{
    protected String serverUrl;

    protected String appKey;

    protected String appSecret;

    protected String format = "xml";

    protected String signMethod = "md5";

    protected int connectTimeout = 15000;

    protected int readTimeout = 30000;

    protected boolean needEnableParser = true;

    protected boolean useGzipEncoding = true;

    private boolean isHttpDnsEnabled = false;

    private String originalHttpHost = null;

    public CustomerQimenClient(String serverUrl, String appKey, String appSecret)
    {
        this.appKey = appKey;
        this.appSecret = appSecret;
        this.serverUrl = serverUrl;
    }

    public <T extends QimenResponse> T execute(QimenRequest<T> request)
        throws ApiException
    {
        return this.execute(request, (String)null);
    }

    public <T extends QimenResponse> T execute(QimenRequest<T> request, String session)
        throws ApiException
    {
        return this._execute(request, session);
    }

    private <T extends QimenResponse> T _execute(QimenRequest<T> request, String session)
        throws ApiException
    {
        long start = System.currentTimeMillis();
        RequestParametersHolder requestHolder = new RequestParametersHolder();
        requestHolder.setApplicationParams(request.getQueryParams());
        TaobaoHashMap protocalMustParams = new TaobaoHashMap();
        protocalMustParams.put("method", request.getApiMethodName());
        protocalMustParams.put("v", request.getVersion());
        protocalMustParams.put("app_key", this.appKey);
        Long timestamp = request.getTimestamp();
        if (timestamp == null)
        {
            timestamp = System.currentTimeMillis();
        }

        protocalMustParams.put("timestamp", new Date(timestamp));
        requestHolder.setProtocalMustParams(protocalMustParams);
        TaobaoHashMap protocalOptParams = new TaobaoHashMap();
        protocalOptParams.put("format", this.format);
        protocalOptParams.put("sign_method", this.signMethod);
        protocalOptParams.put("session", session);
        protocalOptParams.put("partner_id", "top-sdk-java-20190305");
        protocalOptParams.put("customerId", request.getCustomerId());
        requestHolder.setProtocalOptParams(protocalOptParams);

        XmlWriter writer;
        try
        {
            String apiBody = request.getBody();
            if (StringUtils.isEmpty(apiBody))
            {
                writer = new XmlWriter(true, "request", QimenRequest.class);
                apiBody = writer.write(request);
            }

            protocalMustParams.put("sign",
                TaobaoUtils.signTopRequestWithBody(requestHolder, apiBody, this.appSecret, this.signMethod));
            String sysMustQuery = WebUtils.buildQuery(requestHolder.getProtocalMustParams(), "UTF-8");
            String sysOptQuery = WebUtils.buildQuery(requestHolder.getProtocalOptParams(), "UTF-8");
            String realServerUrl = this.getServerUrl(this.serverUrl);
            String fullUrl = WebUtils.buildRequestUrl(realServerUrl, new String[] {sysMustQuery, sysOptQuery});
            TaobaoHashMap headerMap = new TaobaoHashMap();
            if (this.useGzipEncoding)
            {
                headerMap.put("Accept-Encoding", "gzip");
            }

            if (this.getTopHttpDnsHost() != null)
            {
                headerMap.put("TOP_HTTP_DNS_HOST", this.getTopHttpDnsHost());
            }
            BaseContextHandler.set("url",fullUrl);
            BaseContextHandler.set("request",apiBody);
            HttpResponseData data = WebV2Utils.doPost(fullUrl,
                "text/xml;charset=utf-8",
                apiBody.getBytes("UTF-8"),
                this.connectTimeout,
                this.readTimeout,
                headerMap,
                (Proxy)null);
            requestHolder.setResponseBody(data.getBody());
            requestHolder.setResponseHeaders(data.getHeaders());
            BaseContextHandler.set("response",data.getBody());
        }
        catch (IOException var17)
        {
            BaseContextHandler.set("response",var17.toString());
            TaobaoLogger.logApiError(this.appKey,
                request.getApiMethodName(),
                this.serverUrl,
                requestHolder.getAllParams(),
                System.currentTimeMillis() - start,
                var17.toString());
            throw new ApiException(var17);
        }

        TaobaoParser<T> parser = null;
        if (this.needEnableParser && "xml".equals(this.format))
        {
            parser = new QimenXmlParser(request.getResponseClass());
        }

        T tRsp = null;
        if (this.needEnableParser)
        {
            tRsp = parser.parse(requestHolder.getResponseBody(), Constants.RESPONSE_TYPE_QIMEN);
        }
        else
        {
            try
            {
                tRsp = request.getResponseClass().newInstance();
                tRsp.setBody(requestHolder.getResponseBody());
            }
            catch (Exception e)
            {
                throw new ApiException(e);
            }
        }

        if (!tRsp.isSuccess())
        {
            TaobaoLogger.logApiError(appKey,
                request.getApiMethodName(),
                serverUrl,
                requestHolder.getAllParams(),
                System.currentTimeMillis() - start,
                tRsp.getBody());
        }
        return tRsp;
    }

    public void setNeedEnableParser(boolean needEnableParser)
    {
        this.needEnableParser = needEnableParser;
    }

    public void setNeedEnableLogger(boolean needEnableLogger)
    {
        TaobaoLogger.setNeedEnableLogger(needEnableLogger);
    }

    public void setIgnoreSSLCheck(boolean ignore)
    {
        WebUtils.setIgnoreSSLCheck(ignore);
    }

    public void setUseGzipEncoding(boolean useGzipEncoding)
    {
        this.useGzipEncoding = useGzipEncoding;
    }

    public void setConnectTimeout(int connectTimeout)
    {
        this.connectTimeout = connectTimeout;
    }

    public void setReadTimeout(int readTimeout)
    {
        this.readTimeout = readTimeout;
    }

    public String getServerUrl(String serverUrl)
    {
        if (this.isHttpDnsEnabled)
        {
            DnsConfig dnsConfig = ClusterManager.GetDnsConfigFromCache();
            return dnsConfig == null ? serverUrl : dnsConfig.getVipUrl(serverUrl);
        }
        else
        {
            return serverUrl;
        }
    }

    public String getTopHttpDnsHost()
    {
        return this.isHttpDnsEnabled ? this.originalHttpHost : null;
    }

    public void enableHttpDns()
    {
        WebUtils.setIgnoreHostCheck(true);
        this.setHttpDnsHost(this.serverUrl);
        ClusterManager.initRefreshThread(this.appKey, this.appSecret);
        this.isHttpDnsEnabled = true;
    }

    public void enableHttpDns(String onlineAppKey, String onlineAppSecret)
    {
        WebUtils.setIgnoreHostCheck(true);
        this.setHttpDnsHost(this.serverUrl);
        ClusterManager.initRefreshThread(onlineAppKey, onlineAppSecret);
        this.isHttpDnsEnabled = true;
    }

    private void setHttpDnsHost(String serverUrl)
    {
        if (serverUrl != null)
        {
            try
            {
                URL url = new URL(serverUrl);
                this.originalHttpHost = url.getHost();
            }
            catch (Exception var3)
            {
                throw new RuntimeException("error serverUrl:" + serverUrl, var3);
            }
        }
    }
}

